package test2;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: ZhongJinTao
 * Date: 2024-03-14
 * Time: 23:01
 */
public class TchEchoServer2 {
    ServerSocket socket = null;

    public TchEchoServer2(int serverPort) throws IOException {
        socket = new ServerSocket(serverPort);
    }

    public void start() throws IOException {
        System.out.println("服务器启动");
//        ExecutorService pool = Executors.newCachedThreadPool();
        while (true) {
            Socket clientSocket = socket.accept();
            Thread t = new Thread(() -> {
                processConnection(clientSocket);
            });
            t.start();
//            pool.submit(new Runnable() {
//                @Override
//                public void run() {
//                    processConnection(clientSocket);
//                }
//            });
        }
    }

    public void processConnection(Socket clientSocket){
        try(InputStream inputStream = clientSocket.getInputStream();
            OutputStream outputStream = clientSocket.getOutputStream()) {
            while (true) {
                Scanner scanner = new Scanner(inputStream);
                //1、接收客户端发来的请求
                if(!scanner.hasNext()) {
                    System.out.printf("[%s : %d], 客户端下线", clientSocket.getInetAddress(),
                            clientSocket.getPort());
                    break;
                }
                String request = scanner.next();
                //2、计算请求
                String response = process(request);
                //3、根据请求构造响应，返回响应
                PrintWriter writer = new PrintWriter(outputStream);
                writer.println(response);
                 //刷新缓冲区
                writer.flush();
                System.out.printf("[%s : %d] req: %s resp: %s", clientSocket.getInetAddress(),
                        clientSocket.getPort(), request, response);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                clientSocket.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

    public String process(String request) {
        return request;
    }

    public static void main(String[] args) throws IOException {
        TchEchoServer2 tchEchoServer2 = new TchEchoServer2(9090);
        tchEchoServer2.start();
    }
}
